package com.paic.mhis.hcpms.quota.exportword.itext;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.lowagie.text.BadElementException;
import com.paic.mhis.core.exception.FwaBusinessException;
import com.paic.mhis.hcpms.common.community.dto.MedicalOrgInfoDTO;
import com.paic.mhis.hcpms.quota.exportword.biz.service.QueryKpiQuotaDataService;
import com.paic.mhis.hcpms.quota.exportword.dao.WordDataDao;
import com.paic.mhis.hcpms.quota.exportword.dto.KpiBatchDTO;
import com.paic.mhis.hcpms.quota.exportword.utils.GeneralMethods;
import com.paic.mhis.hcpms.quota.settlement.common.KpiValueConst;

/**
 * 创建rtf文档
 * 
 * @author: EX-XIONGFEI002
 * @version:
 */
@Component("rtfCreatorHelper")
public class RtfCreatorHelper {

	private static final Logger LOGGER = Logger.getLogger(RtfCreatorHelper.class);

	@Value("${rtfFileDownloadPath}")
	private String rtfReportDir;

	@Value("${rtfReportTemplatePath}")
	private String rtfReportTemplatePath;

	@Autowired
	private QueryKpiQuotaDataService queryKpiQuotaDataService;

	@Autowired
	private WordDataDao wordDataDao;

	/**
	 * 配置相关信息
	 * 
	 * @throws FwaBusinessException
	 */
	private String getTemplatePath(String templateName) {
		return rtfReportTemplatePath + CreateRtfTableDataHelper.TEMPLEATE_DIR + templateName;
	}

	/**
	 * 获取模板内容
	 * 
	 * @param modelPath
	 *            rtf模板路径
	 * @return 模板内容
	 */
	private String getRtfModelContent(String modelPath) {
		StringBuffer source = new StringBuffer(1024);
		InputStream ins = null;
		try {
			ins = new FileInputStream(modelPath);
			byte[] b = new byte[1024];
			int bytesRead = 0;
			while ((bytesRead = ins.read(b, 0, 1024)) != -1) {
				source.append(new String(b, 0, bytesRead));
			}
		} catch (Exception e) {
			LOGGER.error("--getRtfModelContent ----", e);
		} finally {
			try {
				if (ins != null) {
					ins.close();
				}
			} catch (IOException e) {
			}
		}
		return source.toString();
	}

	/**
	 * 替换img 及字符串
	 * 
	 * @param content
	 *            进行内容转化
	 * @param text
	 *            值
	 * @param maker
	 *            key
	 * @return 替换后的内容
	 */
	private String replaceRtfContent(String content, String text, String maker) {
		String result = content;
		if (maker.endsWith("img") || maker.endsWith("img_end")) {
			result = content.replace(maker, this.getImgRtfCode2(text));
		} else if (maker.endsWith("table_end") || maker.endsWith("table")) {
			// table的内容在前面就已经转换过了，这里不需要再转了
			result = content.replace(maker, text);
		} else {
			// List的都是曲线图上的曲线，用来生成jfreechart图片的，这里不处理，其他的都处理
			if (!maker.endsWith("List_end")) {
				result = content.replace(maker, this.getStrRtfCode(text));
			}
		}
		return result;
	}

	/**
	 * getStrRtfCode
	 * 
	 * @param content
	 *            string格式的rtf内容
	 * @return 转化后的rtf内容
	 */
	private String getStrRtfCode(String content) {
		if (GeneralMethods.getInstance().isEmptyString(content)) {
			content = "";
		}

		char[] digital = "0123456789ABCDEF".toCharArray();
		StringBuffer sb = new StringBuffer("");
		byte[] bs = null;
		try {
			bs = content.getBytes("GB2312");
			int bit;
			for (int i = 0; i < bs.length; i++) {
				bit = (bs[i] & 0x0f0) >> 4;
				sb.append("\\loch\\af0\\hich\\af0\\dbch\\f13 ");
				sb.append("\\'");
				sb.append(digital[bit]);
				bit = bs[i] & 0x0f;
				sb.append(digital[bit]);
			}
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("--getStrRtfCode ----", e);
		}

		return sb.toString();
	}

	/**
	 * 在itext2.1.7版本中获取image图片code的方法
	 */
	private String getImgRtfCode2(String imageName) {

		if (GeneralMethods.getInstance().isEmptyString(imageName)) {
			return getStrRtfCode("");
		}

		FileInputStream fis = null;
		java.io.ByteArrayOutputStream bos = null;
		StringBuffer buffer = new StringBuffer(1024);
		try {
			// fis = new FileInputStream(this.getImagePath(imageName));
			fis = new FileInputStream(imageName);
			BufferedInputStream bis = new BufferedInputStream(fis);
			bos = new java.io.ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int len = 0;
			while ((len = bis.read(buff)) != -1) {
				bos.write(buff, 0, len);
			}

			// 得到图片的字节数组
			byte[] result = bos.toByteArray();
			// 字节数组转成十六进制
			buffer.append("{\\*\\shppict{\\pict\\jpegblip\\picw16\\pich16 ").append(byte2HexStr(result)).append("}}");
		} catch (FileNotFoundException e) {
			LOGGER.error("--getImgRtfCode2 ----", e);
			buffer.append("");
		} catch (IOException e) {
			LOGGER.error("--getImgRtfCode2 ----", e);
			buffer.append("");
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				LOGGER.error("close --IOException ----", e);
			}
			try {
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				LOGGER.error("close --IOException ----", e);
			}
		}

		return buffer.toString();
	}

	/**
	 * 实现字节数组向十六进制的转换方法一
	 */
	private String byte2HexStr(byte[] b) {
		StringBuffer hs = new StringBuffer(1024);
		for (int n = 0; n < b.length; n++) {
			String stmp = Integer.toHexString(b[n] & 0XFF);
			if (stmp.length() == 1) {
				hs.append("0").append(stmp);
			} else {
				hs.append(stmp);
			}
		}
		return hs.toString().toUpperCase();
	}

	/**
	 * 第三部分
	 * 
	 * @param medicalOrgInfoDTO
	 *            medicalOrgInfoDTO
	 * @param resultMap
	 *            resultMap
	 * @param kpiQuotaLimitMap
	 *            kpiQuotaLimitMap
	 * @param kpiBatchDTO
	 *            kpiBatchDTO
	 */
	private void getThirdPartyData(MedicalOrgInfoDTO medicalOrgInfoDTO, Map<String, Object> resultMap,
			Map<String, Object> kpiQuotaLimitMap, KpiBatchDTO kpiBatchDTO) {

		LOGGER.info("load rtf file third party data start...");

		final String type = "2";
		// 2.1、医疗总费用
		queryKpiQuotaDataService.getTotFeeData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getMedFeeData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		queryKpiQuotaDataService.getHospFeeData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getRateMedFeeData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		
		// 2.2 单一机构月度审查
		queryKpiQuotaDataService.getHosMonthCheckFee(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO));

		// 2、住院
		// 高海光 药品和其他
		queryKpiQuotaDataService.getDrugFeeData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getOtherFeeData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		// 3、住院:出院人次 ,平均花费
		queryKpiQuotaDataService.getDischargePeoplesData(resultMap,
				getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO), kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getTimesCostData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		// 4、平均床日费和平均住院日
		queryKpiQuotaDataService.getAvgHospBedDayData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getCostPerBedDayData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		// 二、门诊
		// 1、门诊总费用和医保占比
		queryKpiQuotaDataService.getOutpatFeeData(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getRateMedFeeInOutpatData(resultMap,
				getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO), kpiQuotaLimitMap, kpiBatchDTO);

		// 2、药品和其他
		queryKpiQuotaDataService.getDrugFeeInOutpatData(resultMap,
				getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO), kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getOtherFeeInOutpatData(resultMap,
				getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO), kpiQuotaLimitMap, kpiBatchDTO);

		// 3、门诊人次和次均费用
		queryKpiQuotaDataService.getDischargePeoplesInOutpatData(resultMap,
				getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO), kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getAvgOneTimesFeeInOutpatData(resultMap,
				getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO), kpiQuotaLimitMap, kpiBatchDTO);

		// 4、门诊人数和人均费用
		queryKpiQuotaDataService.getPeopleTimesOutpatData(resultMap,
				getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO), kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getAvgPeopleTimesFeeInOutpatData(resultMap,
				getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO), kpiQuotaLimitMap, kpiBatchDTO);

		// 5、各科室对比
		queryKpiQuotaDataService.getWordDeptsContrast(resultMap, getPartyParams(medicalOrgInfoDTO, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		LOGGER.debug("load rtf file third party data finish");

	}

	private Map<String, Object> getPartyParams(MedicalOrgInfoDTO medicalOrgInfoDTO, String type, KpiBatchDTO kpiBatchDTO) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("currentDate", kpiBatchDTO.getKpiTime());
		paramMap.put("regionCode", kpiBatchDTO.getRegionCode());
		paramMap.put("type", type);
		paramMap.put("medicalOrgCode", medicalOrgInfoDTO == null ? null : medicalOrgInfoDTO.getMedicalOrgCode());

		return paramMap;
	}

	/**
	 * 第二部分数据
	 * 
	 * @param resultMap
	 *            resultMap
	 * @param limitMap
	 *            limitMap
	 * @param kpiBatchDTO
	 *            kpiBatchDTO
	 * @throws BadElementException
	 * 
	 */
	private void getSecondPartyData(Map<String, Object> resultMap, Map<String, Object> limitMap, KpiBatchDTO kpiBatchDTO)
			throws BadElementException {
		LOGGER.info("load rtf file second party data start...");

		final String type = "1";
		// 2.1、医疗总费用
		queryKpiQuotaDataService.getTotFeeAndMedFeeRate(resultMap, getPartyParams(null, type, kpiBatchDTO), limitMap);

		// 1. 住院费用和医保费用占比
		queryKpiQuotaDataService.getHospFeeAndMedFeeRate(resultMap, getPartyParams(null, type, kpiBatchDTO), limitMap);

		// 2. 住院药品
		queryKpiQuotaDataService.getDrugFeeAndOtherFeeRate(resultMap, getPartyParams(null, type, kpiBatchDTO));

		// 住院：人次和次均费用
		queryKpiQuotaDataService.getDischargePeoplesAndTimesCostFee(resultMap, getPartyParams(null, type, kpiBatchDTO));

		// 郑超：住院：人数和人均费用
		queryKpiQuotaDataService.getAvgHospBedDayFee(resultMap, getPartyParams(null, type, kpiBatchDTO));

		// 2. 门诊费用和医保费用占比
		queryKpiQuotaDataService
				.getOutpatFeeAndMedFeeRate(resultMap, getPartyParams(null, type, kpiBatchDTO), limitMap);

		// 门诊：药品费用
		queryKpiQuotaDataService.getDrugFeeAndOtherFeeInOutpat(resultMap, getPartyParams(null, type, kpiBatchDTO));
		//
		// // 门诊：人次和次均费用
		queryKpiQuotaDataService.getPeopleTimesAndTimeCostInOutpat(resultMap, getPartyParams(null, type, kpiBatchDTO));
		// 郑超：门诊：人数和人均费用
		queryKpiQuotaDataService.getPeoplesAndPeopleFeeInOutpat(resultMap, getPartyParams(null, type, kpiBatchDTO));

		LOGGER.info("load rtf file second party data finish");

	}

	/**
	 * 第一部分数据
	 * 
	 * @param resultMap
	 *            resultMap
	 * @param kpiQuotaLimitMap
	 *            kpiQuotaLimitMap
	 * @param kpiBatchDTO
	 *            kpiBatchDTO
	 * 
	 */
	private void getFirstPartyData(Map<String, Object> resultMap, Map<String, Object> kpiQuotaLimitMap,
			KpiBatchDTO kpiBatchDTO) {
		final String type = "0";
		// 1、医疗总费用
		queryKpiQuotaDataService.getTotFeeData(resultMap, getPartyParams(null, type, kpiBatchDTO), kpiQuotaLimitMap,
				kpiBatchDTO);
		queryKpiQuotaDataService.getMedFeeData(resultMap, getPartyParams(null, type, kpiBatchDTO), kpiQuotaLimitMap,
				kpiBatchDTO);

		// 2、住院
		queryKpiQuotaDataService.getHospFeeData(resultMap, getPartyParams(null, type, kpiBatchDTO), kpiQuotaLimitMap,
				kpiBatchDTO);
		queryKpiQuotaDataService.getRateMedFeeData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		// // 3、药品
		queryKpiQuotaDataService.getDrugFeeData(resultMap, getPartyParams(null, type, kpiBatchDTO), kpiQuotaLimitMap,
				kpiBatchDTO);
		queryKpiQuotaDataService.getOtherFeeData(resultMap, getPartyParams(null, type, kpiBatchDTO), kpiQuotaLimitMap,
				kpiBatchDTO);

		// // 张纪成:人次和次均费用
		queryKpiQuotaDataService.getDischargePeoplesData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getTimesCostData(resultMap, getPartyParams(null, type, kpiBatchDTO), kpiQuotaLimitMap,
				kpiBatchDTO);

		// // 郑超:平均住院日和每床日费用
		queryKpiQuotaDataService.getAvgHospBedDayData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getCostPerBedDayData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		// // 3、门诊
		queryKpiQuotaDataService.getOutpatFeeData(resultMap, getPartyParams(null, type, kpiBatchDTO), kpiQuotaLimitMap,
				kpiBatchDTO);
		queryKpiQuotaDataService.getRateMedFeeInOutpatData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		// 4、药品
		queryKpiQuotaDataService.getDrugFeeInOutpatData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getOtherFeeInOutpatData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		// // 张纪成：门诊：人次和次均费用
		queryKpiQuotaDataService.getDischargePeoplesInOutpatData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getAvgOneTimesFeeInOutpatData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);

		// // 郑超：门诊：人数和人均费用
		queryKpiQuotaDataService.getPeopleTimesOutpatData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		queryKpiQuotaDataService.getAvgPeopleTimesFeeInOutpatData(resultMap, getPartyParams(null, type, kpiBatchDTO),
				kpiQuotaLimitMap, kpiBatchDTO);
		// 基金
		queryKpiQuotaDataService.getFundData(resultMap, getPartyParams(null, type, kpiBatchDTO), kpiQuotaLimitMap,
				kpiBatchDTO);

		LOGGER.info("load rtf file first party data finish");
	}

	/**
	 * 获取医院月度报告数据
	 * 
	 * @param medicalOrgInfoDTO
	 *            medicalOrgInfoDTO
	 * @param resultMap
	 *            resultMap
	 * @param kpiQuotaLimitMap
	 *            kpiQuotaLimitMap
	 * @param kpiBatchDTO
	 *            kpiBatchDTO
	 * @return map
	 */
	public void getHospPartysDataMap(MedicalOrgInfoDTO medicalOrgInfoDTO, Map<String, Object> resultMap,
			Map<String, Object> kpiQuotaLimitMap, KpiBatchDTO kpiBatchDTO) {

		// 3、构造第三部分数据
		getThirdPartyData(medicalOrgInfoDTO, resultMap, kpiQuotaLimitMap, kpiBatchDTO);
	}

	/**
	 * 构造rtf内容
	 * 
	 * @param paramMap
	 *            写入到模板的键值对
	 * @param templateName
	 *            模板名称
	 * @return 模板名称
	 */
	@SuppressWarnings("rawtypes")
	private String replaceRefContent(Map<String, Object> paramMap, String templateName) throws FwaBusinessException {

		LOGGER.info("replace rtf file content is start...");

		String content = this.getRtfModelContent(getTemplatePath(templateName));

		for (Iterator<?> iter = paramMap.entrySet().iterator(); iter.hasNext();) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String) entry.getKey();
			String val = String.valueOf(entry.getValue());
			content = this.replaceRtfContent(content, val, key);

			if (!StringUtils.hasText(content)) {
				LOGGER.error("is error for replace the context,current context is null");
				break;
			}
		}

		LOGGER.info("replace rtf file content is finish");

		return content;
	}

	/**
	 * 写文件,并记录到数据库
	 * 
	 * @param medicalOrgInfoDTO
	 *            机构dto
	 * @param fileName
	 *            文件名
	 * @param content
	 *            内容
	 * @param kpiBatchDTO
	 *            批次dto
	 * @throws FwaBusinessException
	 *             fwaexception
	 */
	private void createRTFFile(MedicalOrgInfoDTO medicalOrgInfoDTO, String fileName, String content,
			KpiBatchDTO kpiBatchDTO, String fileType) throws FwaBusinessException {

		LOGGER.info("createRTFFile start.............");

		writeRtfFile(medicalOrgInfoDTO, content, fileName, kpiBatchDTO);

		// 写文件
		if (kpiBatchDTO.getTmpBatch() != null && !"".equals(kpiBatchDTO.getTmpBatch())) {
			// 记录文件信息到db
			recordeDocToDB(medicalOrgInfoDTO, fileName, kpiBatchDTO, fileType);
		}

		LOGGER.info("createRTFFile end.............");
	}

	/**
	 * 生成rtf文件
	 * 
	 * @param content
	 *            文件内容
	 */
	private void writeRtfFile(MedicalOrgInfoDTO medicalOrgInfoDTO, String content, String fileName,
			KpiBatchDTO kpiBatchDTO) throws FwaBusinessException {

		// write rtf file
		String outputPath = CreateRtfTableDataHelper.getInstance().createRtfOutputFileDir(kpiBatchDTO,
				medicalOrgInfoDTO, rtfReportDir);

		FileOutputStream os = null;
		try {
			os = new FileOutputStream(outputPath + fileName);
			os.write(content.getBytes("GB2312"));

			LOGGER.info("write rtf file content is finish,filePath = " + outputPath + fileName);
		} catch (IOException e) {
			LOGGER.error("write rtf file is failed.", e);
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				LOGGER.error("writeRtfFile IOException.", e);
			}
		}
	}

	/**
	 * 将生成的文件信息记录到数据库
	 * 
	 * @param medicalOrgInfoDTO
	 *            医疗机构信息
	 * @param fileName
	 *            文件名
	 * @param baseDTO
	 *            统筹区信息
	 * @param fileType
	 *            文件类型
	 */
	@Transactional
	private void recordeDocToDB(MedicalOrgInfoDTO medicalOrgInfoDTO, String fileName, KpiBatchDTO kpiBatchDTO,
			String fileType) {

		LOGGER.info("recordeDocToDB start.............");

		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("regionCode", kpiBatchDTO.getRegionCode());
		paramMap.put("docTime", kpiBatchDTO.getKpiTime());
		paramMap.put("providerCode", medicalOrgInfoDTO == null ? null : medicalOrgInfoDTO.getMedicalOrgCode());
		wordDataDao.deleteDocRecord(paramMap);

		paramMap.put("fileName", fileName);
		paramMap.put("fileType", fileType);
		wordDataDao.insertDocRecord(paramMap);

		LOGGER.info("recordeDocToDB end.............");
	}

	/**
	 * 写rtf文件的第三部分
	 * 
	 * @param medicalOrgInfoDTO
	 *            medicalOrgInfoDTO
	 * @param paramMap
	 *            paramMap
	 * @param baseDTO
	 *            baseDTO
	 * @param commonDataMap
	 *            commonDataMap
	 * @param kpiBatchDTO
	 *            kpiBatchDTO
	 * 
	 */
	public void createHospPartyRtf(MedicalOrgInfoDTO medicalOrgInfoDTO, Map<String, Object> paramMap,
			Map<String, Object> kpiQuotaLimitMap, KpiBatchDTO kpiBatchDTO) {
		LOGGER.info("get hospital party data is start,orgCode = " + medicalOrgInfoDTO.getCodeNo());

		try {
			// 3、获取第二和第三部分的医院月度报告数据
			getHospPartysDataMap(medicalOrgInfoDTO, paramMap, kpiQuotaLimitMap, kpiBatchDTO);

			// todo替换星星的判断
			toSetUnNormalStars(paramMap);
			// 1、报告名称 :医院名称-年月.rtf
			String fileName = medicalOrgInfoDTO.getMedicalOrgCode() + "-" + kpiBatchDTO.getKpiTime() + ".rtf";

			// 替换内容
			String rtfContent = replaceRefContent(paramMap, "job_itext_rtf_template_2.rtf");

			createRTFFile(medicalOrgInfoDTO, fileName, rtfContent, kpiBatchDTO, KpiValueConst.FILE_TYPE_HOSP);

		} catch (Exception e) {
			LOGGER.error("create rtf file is failed.", e);
		}

		LOGGER.info("get hospital party data is end,orgCode = " + medicalOrgInfoDTO.getCodeNo());

	}

	/**
	 * 取rtf文件的第一、二部分数据
	 * 
	 * @param paramMap
	 *            paramMap
	 * @param regionCodeDTO
	 *            regionCodeDTO
	 * @param kpiQuotaLimitMap
	 *            kpiQuotaLimitMap
	 * @param kpiBatchDTO
	 *            kpiBatchDTO
	 * @return map
	 * 
	 */
	private void getCommonDataMap(Map<String, Object> paramMap, Map<String, Object> kpiQuotaLimitMap,
			KpiBatchDTO kpiBatchDTO) {
		LOGGER.info("get common Date start.....");
		// 1、构造第一部分
		getFirstPartyData(paramMap, kpiQuotaLimitMap, kpiBatchDTO);

		// 2、构造第二部分数据
		try {
			getSecondPartyData(paramMap, kpiQuotaLimitMap, kpiBatchDTO);
		} catch (BadElementException e) {
			LOGGER.error("------getSecondPartyData---", e);
		}

		LOGGER.info("get common Date end.....,regionCode = " + kpiBatchDTO.getRegionCode());

	}

	/**
	 * 写第一部分的医保月度报告
	 * 
	 * @param paramMap
	 *            paramMap
	 * @param baseDTO
	 *            baseDTO
	 * @param commonDataMap
	 *            commonDataMap
	 * @param kpiBatchDTO
	 *            kpiBatchDTO
	 */
	public void createMedicarePartyRtf(Map<String, Object> paramMap, Map<String, Object> kpiQuotaLimitMap,
			KpiBatchDTO kpiBatchDTO) {
		LOGGER.info("update batch success, get common data is start,regionCode = " + kpiBatchDTO.getRegionCode());

		try {
			getCommonDataMap(paramMap, kpiQuotaLimitMap, kpiBatchDTO);

			// 异常星星
			toSetUnNormalStars(paramMap);

			// 替换内容
			String rtfContent = replaceRefContent(paramMap, "job_itext_rtf_template_1.rtf");

			// 1、报告名称 :结算分析报告-医院名称-年月.rtf
			String fileName = kpiBatchDTO.getRegionCode() + "-" + kpiBatchDTO.getKpiTime() + ".rtf";

			// 写文件并记录doc记录
			createRTFFile(null, fileName, rtfContent, kpiBatchDTO, KpiValueConst.FILE_TYPE_MEDICARE);

		} catch (Exception e) {
			LOGGER.error("create fist party rtf file is failed.", e);
		}

		LOGGER.info("create fist party rtf file end.....");
	}

	private void toSetUnNormalStars(Map<String, Object> paramMap) {
		setUnNormalStar(paramMap, "k0_1_1_2_health_flag_end", "k0_1_1_2_Fee_Rate_img_end");
		setUnNormalStar(paramMap, "k0_1_1_1_health_flag_end", "k0_1_1_1_totalFee_img_end");
		setUnNormalStar(paramMap, "k0_2_1_1_fee_health_flag_end", "k0_2_1_1_fee_img_end");
		setUnNormalStar(paramMap, "k0_2_2_1_Fee_health_flag_end", "k0_2_2_1_Fee_img_end");
		setUnNormalStar(paramMap, "k0_2_1_2_f_health_flag_end", "k0_2_1_2_f_img_end");
		setUnNormalStar(paramMap, "k0_2_2_2_fee_health_flag_end", "k0_2_2_2_fee_img_end");
		setUnNormalStar(paramMap, "k0_2_3_1_times_health_flag_end", "k0_2_3_1_times_img_end");
		setUnNormalStar(paramMap, "k0_2_3_2_fee_health_flag_end", "k0_2_3_2_fee_img_end");
		setUnNormalStar(paramMap, "k0_2_4_1_days_health_flag_end", "k0_2_4_1_days_img_end");
		setUnNormalStar(paramMap, "k0_2_4_2_fee_health_flag_end", "k0_2_4_2_fee_img_end");
		setUnNormalStar(paramMap, "k0_3_1_1_fee_health_flag_end", "k0_3_1_1_fee_img_end");
		setUnNormalStar(paramMap, "k0_3_1_2_f_health_flag_end", "k0_3_1_2_fee_Rate_img_end");
		setUnNormalStar(paramMap, "k0_3_2_1_fee_health_flag_end", "k0_3_2_1_fee_img_end");
		setUnNormalStar(paramMap, "k0_3_2_2_health_flag_end", "k0_3_2_2_fee_img_end");
		setUnNormalStar(paramMap, "k0_3_3_1_times_health_flag_end", "k0_3_3_1_times_img_end");
		setUnNormalStar(paramMap, "k0_3_3_2_fee_health_flag_end", "k0_3_3_2_fee_img_end");
		setUnNormalStar(paramMap, "k0_3_4_1_times_health_flag_end", "k0_3_4_1_times_img_end");
		setUnNormalStar(paramMap, "k0_3_4_2_fee_health_flag_end", "k0_3_4_2_fee_img_end");
		setUnNormalStar(paramMap, "k2_1_1_1_health_flag_end", "k2_1_1_1_totalFee_img_end");
		setUnNormalStar(paramMap, "k2_1_1_2_health_flag_end", "k2_1_1_2_fee_Rate_img_end");
		setUnNormalStar(paramMap, "k2_2_1_1_fee_health_flag_end", "k2_2_1_1_fee_img_end");
		setUnNormalStar(paramMap, "k2_2_1_2_f_health_flag_end", "k2_2_1_2_f_img_end");
		setUnNormalStar(paramMap, "k2_2_2_1_Fee_health_flag_end", "k2_2_2_1_Fee_img_end");
		setUnNormalStar(paramMap, "k2_2_2_2_fee_health_flag_end", "k2_2_2_2_fee_img_end");
		setUnNormalStar(paramMap, "k2_2_3_1_times_health_flag_end", "k2_2_3_1_times_img_end");
		setUnNormalStar(paramMap, "k2_2_3_2_fee_health_flag_end", "k2_2_3_2_fee_img_end");
		setUnNormalStar(paramMap, "k2_2_4_1_days_health_flag_end", "k2_2_4_1_days_img_end");
		setUnNormalStar(paramMap, "k2_2_4_2_fee_health_flag_end", "k2_2_4_2_fee_img_end");
		setUnNormalStar(paramMap, "k2_3_1_1_fee_health_flag_end", "k2_3_1_1_fee_img_end");
		setUnNormalStar(paramMap, "k2_3_1_2_f_health_flag_end", "k2_3_1_2_f_img_end");
		setUnNormalStar(paramMap, "k2_3_2_1_Fee_health_flag_end", "k2_3_2_1_Fee_img_end");
		setUnNormalStar(paramMap, "k2_3_2_2_fee_health_flag_end", "k2_3_2_2_fee_img_end");
		setUnNormalStar(paramMap, "k2_3_3_1_times_health_flag_end", "k2_3_3_1_times_img_end");
		setUnNormalStar(paramMap, "k2_3_3_2_fee_health_flag_end", "k2_3_3_2_fee_img_end");
		setUnNormalStar(paramMap, "k2_3_4_1_days_health_flag_end", "k2_3_4_1_days_img_end");
		setUnNormalStar(paramMap, "k2_3_4_2_fee_health_flag_end", "k2_3_4_2_fee_img_end");
	}

	private void setUnNormalStar(Map<String, Object> paramMap, String key1, String key2) {
		if (paramMap.get(key1) == null) {
			return;
		}
		if ("".equals(((String) paramMap.get(key1)).trim()) || "无明显异常".equals(paramMap.get(key1))) {
			paramMap.put(key2, "");
		}
	}
}
